package cc.miwuya.complain.controller;

import cc.miwuya.common.util.JwtUtils;
import cc.miwuya.common.util.Result;
import cc.miwuya.complain.domain.Notice;
import cc.miwuya.complain.service.NoticeService;
import cc.miwuya.core.BaseController;
import cn.hutool.core.lang.Assert;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @Author 迷雾森林
 * @Date 2024-02-24 10:29
 * 公告控制器
 */
@RestController
@RequestMapping("/common/notice")
public class NoticeController extends BaseController {
    @Resource
    NoticeService noticeService;
    @Resource
    HttpServletRequest httpServletRequest;
    /**
     * 获取公告列表
     */
    @GetMapping("/list")
    public Result list(Long residentialId,String name) {
        return Result.success(noticeService.getPage(getPage(),residentialId,name));
    }

    /**
     * 发布或修改公告
     */
    @PostMapping("/edit")
    public Result edit(@RequestBody Notice notice) {
        notice.setCreated(LocalDateTime.now());
        notice.setOperatorId(getCurrent());
        boolean update = noticeService.saveOrUpdate(notice);
        if (update) {
            return Result.success();
        }
        return Result.error();
    }

    /**
     * 根据ID获取公告信息
     */
    @GetMapping("/info/{id}")
    public Result info(@PathVariable Long id) {
        Notice notice = noticeService.getById(id);
        return Result.success(notice);
    }

    /**
     * 根据Id删除公告
     */
    @GetMapping("/delete/{id}")
    public Result delete(@PathVariable Long id) {
        boolean remove = noticeService.removeById(id);
        if (remove) {
            return Result.success();
        }
        return Result.error("删除失败");
    }
    public Long getCurrent(){
        String authorization = httpServletRequest.getHeader("Authorization");
        Claims claim = JwtUtils.getClaimByToken(authorization, "community");
        JSON parse = JSONUtil.parse(claim);
        System.out.println(parse);
        return Long.parseLong(parse.getByPath("userId").toString());
    }
}
